package com.rc.saas.mini.controller.charge;

import com.github.dozermapper.core.Mapper;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.charge.ChargeService;
import com.rc.saas.mini.charge.ChargeServiceRouter;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.common.constant.WebConstant;
import com.rc.saas.mini.common.utils.HlhtQrCodeUtils;
import com.rc.saas.mini.hlhtcec2.service.HlhtChargeService;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.car.TenantCarNumber;
import com.rc.saas.mini.model.elec.ElecGun;
import com.rc.saas.mini.model.elec.ElecPile;
import com.rc.saas.mini.model.elec.ElecStation;
import com.rc.saas.mini.model.elec.ElecStationPrice;
import com.rc.saas.mini.model.enterprise.EnterpriseSubmember;
import com.rc.saas.mini.model.enterprise.EnterpriseSubmemberApply;
import com.rc.saas.mini.model.enterprise.EnterpriseSubmemberApplyExample;
import com.rc.saas.mini.model.hlht.HlhtOperatorSetting;
import com.rc.saas.mini.model.hlht.HlhtTenantOpen;
import com.rc.saas.mini.model.hlht.HlhtTenantOpenStation;
import com.rc.saas.mini.model.member.MemberAccount;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderComment;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.order.OrderInfoExample;
import com.rc.saas.mini.model.rc.RcSetting;
import com.rc.saas.mini.model.rc.RcSettingExample;
import com.rc.saas.mini.model.ugs.UgsMemberLevelRecord;
import com.rc.saas.mini.search.ElecStationPriceSearch;
import com.rc.saas.mini.service.car.TenantCarNumberService;
import com.rc.saas.mini.service.elec.*;
import com.rc.saas.mini.service.enterprise.EnterpriseSubmemberApplyService;
import com.rc.saas.mini.service.enterprise.EnterpriseSubmemberShareService;
import com.rc.saas.mini.service.hlht.HlhtOperatorSettingService;
import com.rc.saas.mini.service.hlht.HlhtTenantOpenService;
import com.rc.saas.mini.service.hlht.HlhtTenantOpenStationService;
import com.rc.saas.mini.service.member.MemberAccountService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.order.OrderCommentService;
import com.rc.saas.mini.service.order.OrderDiscountRecordService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.rc.RcSettingService;
import com.rc.saas.mini.service.tenant.TenantSettingService;
import com.rc.saas.mini.service.ugs.UgsMemberLevelRecordService;
import com.rc.saas.mini.vo.charge.CommandStartReq;
import com.rc.saas.mini.vo.charge.CommandStopReq;
import com.rc.saas.mini.vo.charge.QrCodeVo;
import com.rc.saas.mini.vo.charge.QueryGunDetailVo;
import com.rc.saas.mini.vo.elec.GunVo;
import com.rc.saas.mini.vo.hlhtcec2.StopChargeResult;
import com.rc.saas.mini.vo.hlhtcec2.WxEquipChargeStatusResult;
import com.rc.saas.mini.vo.hlhtcec2.WxStartChargeResult;
import com.rc.saas.mini.vo.order.OrderDiscountVo;
import com.rc.saas.mini.vo.order.OrderRefreshVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/charge")
@Api(tags = "07.统一充电接口")
public class ChargeController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(ChargeController.class);

    @Autowired
    private Mapper dozerMapper;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private HlhtOperatorSettingService hlhtOperatorSettingService;

    @Autowired
    private HlhtTenantOpenService hlhtTenantOpenService;

    @Autowired
    private HlhtTenantOpenStationService hlhtTenantOpenStationService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ElecStationPriceService elecStationPriceService;

    @Autowired
    private EnterpriseSubmemberService enterpriseSubmemberService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private ChargeServiceRouter chargeServiceRouter;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private OrderCommentService orderCommentService;

    @Autowired
    private QrCodeParser qrCodeParser;

    @Autowired
    private TenantSettingService tenantSettingService;

    @Autowired
    private EnterpriseSubmemberShareService enterpriseSubmemberShareService;

    @Autowired
    private UgsMemberLevelRecordService ugsMemberLevelRecordService;

    @Autowired
    private OrderDiscountRecordService orderDiscountRecordService;

    @Autowired
    private TenantCarNumberService tenantCarNumberService;
    @Autowired
    private ChargeService chargeService;

    @Autowired
    private HlhtChargeService hlhtChargeService;
    @Autowired
    private RcSettingService rcSettingService;
    @Autowired
    private EnterpriseSubmemberApplyService enterpriseSubmemberApplyService;

    /**
     * 充电前检查余额是否充足
     *
     * @param accountType 支付的账户类型 0个人钱包 1企业钱包 默认0
     */
    //@ResponseBody
    //@RequestMapping("/checkStartMemberAccount")
    //@ApiOperation(value = "充电前检查余额是否充足", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "accountType", paramType = "query", value = "支付的账户类型 0个人钱包 1企业钱包", required = true)})
    //public DataTResponse checkStartMemberAccount(String accountType, @ApiIgnore HttpSession session) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    LoginInfoVo loginInfo = readLoginInfo(request);
    //    if (loginInfo == null) {
    //        return DataTResponse.FAIL_LOGIN();
    //    }
    //
    //    MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
    //    if (memberInfo == null) {
    //        return DataTResponse.FAIL_LOGIN();
    //    }
    //    logger.info("ChargeController.checkStartMemberAccount.tenant:{}.mobile:{},accountType:{}", tenantCode, memberInfo.getMobile(), accountType);
    //    //用户账户
    //    MemberAccountExample example = new MemberAccountExample();
    //    example.createCriteria().andMemberIdEqualTo(memberInfo.getMemberId()).andTenantCodeEqualTo(tenantCode);
    //    List<MemberAccount> memberAccounts = memberAccountService.selectByExample(example);
    //    if (memberAccounts == null || memberAccounts.size() == 0) {
    //        return DataTResponse.FAIL("用户账户不存在");
    //    }
    //
    //    //支付的账户类型 0个人钱包 1企业钱包
    //    MemberAccount memberAccount = memberAccounts.get(0);
    //    //单充用户最小启动充电余额
    //    BigDecimal start_charge_account_limit = tenantSettingService.query_start_charge_account_limit(memberInfo.getTenantCode());
    //    //判断是个人钱包还是企业钱包:支付的账户类型 0个人钱包 1企业钱包(不存在共享余额) 2.共享余额
    //    BigDecimal money = null;
    //    if (accountType.equals("1")) {
    //        money = memberAccount.getEnterpriseAccount();
    //    } else if (accountType.equals("0")) {
    //        money = memberAccount.getAccount();
    //    } else {
    //        //查询共享余额
    //        //共享余额
    //        EnterpriseSubmemberShareExample enterpriseSubmemberShareExample = new EnterpriseSubmemberShareExample();
    //        enterpriseSubmemberShareExample.createCriteria().andTenantCodeEqualTo(tenantCode).andMemberIdEqualTo(memberInfo.getMemberId()).andStatusEqualTo("1").andBeginTimeLessThan(new Date()).andEndTimeGreaterThanOrEqualTo(new Date());
    //        List<EnterpriseSubmemberShare> enterpriseSubmemberShares = enterpriseSubmemberShareService.selectByExample(enterpriseSubmemberShareExample);
    //        if (enterpriseSubmemberShares != null && enterpriseSubmemberShares.size() > 0) {
    //            //if (enterpriseSubmemberShares.get(0).getSharePower().compareTo(enterpriseSubmemberShares.get(0).getFixedPower()) != -1) {
    //            //    return DataTResponse.FAIL("当前设置的共享余额的电量值不足,请选择其他支付类型！！");
    //            //}
    //            if (enterpriseSubmemberShares.get(0).getFixedPower().subtract(enterpriseSubmemberShares.get(0).getSharePower()).compareTo(BigDecimal.ONE) == -1) {
    //                return DataTResponse.FAIL("当前设置的共享余额的电量值不足1度，请选择其他支付类型！！");
    //            }
    //            //if (enterpriseSubmemberShares.get(0).getShareAccount().compareTo(enterpriseSubmemberShares.get(0).getFixedAccount()) == -1) {
    //            //    return DataTResponse.FAIL("当前设置的共享余额的金额不足,请选择其他支付类型！！");
    //            //}
    //            if (enterpriseSubmemberShares.get(0).getFixedAccount().subtract(enterpriseSubmemberShares.get(0).getShareAccount()).compareTo(BigDecimal.ONE) == -1) {
    //                return DataTResponse.FAIL("当前设置的共享余额的余额不足1元，请选择其他支付类型！！");
    //            }
    //            money = enterpriseSubmemberShares.get(0).getFixedAccount().subtract(enterpriseSubmemberShares.get(0).getShareAccount());
    //        } else {
    //            return DataTResponse.FAIL("当前没有设置共享余额,请选择其他支付类型！！");
    //        }
    //        //检查主账号是否余额不足
    //        MemberAccount memberAccountEnterprise = memberAccountService.selectByMemberId(tenantCode, memberInfo.getEnterpriseMemberId());
    //        if (memberAccountEnterprise.getEnterpriseAccount().compareTo(start_charge_account_limit) < 0) {
    //            return DataTResponse.FAIL("主会员的企业余额不足");
    //        }
    //
    //    }
    //
    //    //平台参数设置
    //    TenantSetting tenantSetting = tenantSettingService.selectByPrimaryKey(memberInfo.getTenantCode());
    //
    //    // 单充会员判断是否使用中,多充会员忽略;
    //    //(charge_type)充电类型 0单冲  1多充 默认0
    //    //(charge_status)用户是否在充电 0不是，1正充电 默认0
    //    if ("0".equals(memberInfo.getChargeType()) && "1".equals(memberInfo.getChargeStatus())) {  //单充
    //        OrderInfo lastOrderInfo = orderInfoService.selectLastByMember(memberInfo.getMemberId(), memberInfo.getTenantCode());
    //        if (lastOrderInfo == null) {
    //            return DataTResponse.FAIL("单充会员正在使用中");
    //        }
    //
    //        //上笔挂单，但是桩未离线也不允许充电
    //        ElecPile lastElecPile = elecPileService.selectByPrimaryKey(lastOrderInfo.getElecPileId());
    //        if (!WebConstant.CON2.equals(lastOrderInfo.getStatus()) && WebConstant.CON1.equals(lastElecPile.getStatus())) {
    //            return DataTResponse.FAIL("单充会员正在使用中");
    //        }
    //    } else if ("1".equals(memberInfo.getChargeType())) {
    //        Long number = orderInfoService.countElecOrder(memberInfo.getMemberId(), tenantCode) + 1;
    //        if (number > 1) {
    //            BigDecimal startMoney = new BigDecimal(tenantSetting.getStartMultChargeAccountMin()).multiply(new BigDecimal(number));
    //            //多充会员启动的余额大于  单次启动金额*（正在充电订单数+1）
    //            if (startMoney.compareTo(money) == 1) {
    //                return DataTResponse.FAIL("余额不足（一号多充用户" + tenantSetting.getStartMultChargeAccountMin() + "元/车）");
    //            }
    //        }
    //    }
    //    //单充用户最小启动充电余额
    //
    //    //BigDecimal start_charge_account_limit = tenantSettingService.query_start_charge_account_limit(tenantCode);
    //    if (money == null || money.compareTo(start_charge_account_limit) == -1) {
    //        DataTResponse DataTResponse = DataTResponse.FAIL();
    //        DataTResponse.setStatus(400);
    //        DataTResponse.setMessage("余额少于" + start_charge_account_limit + "元");
    //        return DataTResponse;
    //    }
    //    return DataTResponse.SUCCESS();
    //}


    /**
     * 查询当前用户是否有正在充电的订单
     */
    @ResponseBody
    @RequestMapping("/selectChargingOrder")
    @ApiOperation(value = "查询当前用户是否有正在充电的订单", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<List<OrderInfo>> selectChargingOrder(HttpServletRequest request) {

        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        String tenantCode = loginInfo.getTenantCode();

        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (memberInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("ChargeController.selectChargingOrder.tenant:{}.mobile:{}", tenantCode, memberInfo.getMobile());

        List<OrderInfo> orders = orderInfoService.listChargingOrder(memberInfo.getMemberId(), 10, tenantCode);
        return DataTResponse.SUCCESS_DATA(orders);
    }

    /**
     * 充电详情
     */
    @ResponseBody
    @RequestMapping("/query_gun_detail")
    @ApiOperation(value = "充电枪详情（未完成）", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hlhtTenantCode", paramType = "query", value = "SAAS内互联互通的设备商", required = false),
            @ApiImplicitParam(name = "hlhtOperatorId", paramType = "query", value = "第三方互联互通的设备商", required = false),
            @ApiImplicitParam(name = "gunNo", paramType = "query", value = "枪编号", required = false),
            @ApiImplicitParam(name = "qrCode", paramType = "query", value = "二维码", required = false)})
    public DataTResponse<QueryGunDetailVo> query_gun_detail(HttpServletRequest request, String hlhtTenantCode, String hlhtOperatorId, String gunNo, String qrCode) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        String tenantCode = loginInfo.getTenantCode();

        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (memberInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        //充电枪号/二维码不能同时为空
        if (StringUtils.isBlank(gunNo) && StringUtils.isBlank(qrCode)) {
            return DataTResponse.FAIL("充电枪号/二维码不能为空");
        }

        QrCodeVo qrCodeVo = new QrCodeVo();
        //if (StringUtils.isNotBlank(gunNo)) {
        //    qrCodeVo.setGunNo(gunNo);
        //    //第三方互联运营商枪编码兼容
        //    checkGunNo(qrCodeVo);
        //}
        if (qrCode != null) {
            //运营商自己桩群
            gunNo = HlhtQrCodeUtils.parserQrCode(qrCode);
            qrCodeVo.setGunNo(gunNo);
        }

        if (StringUtils.isBlank(qrCodeVo.getGunNo())) {
            return DataTResponse.FAIL("充电枪号/二维码不能为空");
        }

        logger.info("query_gun_detail.request,:{},:{}，：{}", memberInfo.getMemberId(), memberInfo.getTenantCode(), qrCodeVo.getGunNo());

        TResponse tResponse = chargeServiceRouter.query_gun_detail(memberInfo, hlhtTenantCode, qrCodeVo.getHlhtOperatorId(), qrCodeVo.getGunNo(), qrCode);
        //查找枪详情
        DataTResponse dataTResponse = new DataTResponse();
        BeanUtils.copyProperties(tResponse, dataTResponse);
        return dataTResponse;
    }


    /**
     * 扫码充电
     */
    @ResponseBody
    @RequestMapping(value = "/createQrcodeDestFromCec", method = RequestMethod.POST)
    @ApiOperation(value = "扫码充电", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "scanCecQRCode", paramType = "query", value = "二维码数据", required = false),
            @ApiImplicitParam(name = "cecGunNo", paramType = "query", value = "枪编码", required = false)
    })
    public DataTResponse<GunVo> createQrcodeDestFromCec(HttpServletRequest request, String scanCecQRCode, String cecGunNo) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        String tenantCode = loginInfo.getTenantCode();
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("createQrcodeDestFromCec.tenant:{},mobile:{},scanCecQRCode:{},cecGunNo:{}", tenantCode, member.getMobile(), scanCecQRCode, cecGunNo);
        //从中电联二维码链接返回枪号
        String epNo = "";
        QrCodeVo qrCodeVo = new QrCodeVo();
        if (StringUtils.isNotBlank(scanCecQRCode)) {
            epNo = HlhtQrCodeUtils.parserQrCode(scanCecQRCode);
        } else if (StringUtils.isNotBlank(cecGunNo)) {
            epNo = cecGunNo;
        }
        logger.info("createQrcodeDestFromCec.epNo:{}", epNo);
        if (StringUtils.isBlank(epNo)) {
            return DataTResponse.FAIL("无效的二维码或输入枪编码为空！ ");
        }
        ElecGun gun = elecGunService.selectGunByGunNo(epNo);

        if (gun == null) {
            return DataTResponse.FAIL("未找到充电桩");
        } else {
            if (StringUtils.isNotBlank(gun.getHlhtOperatorId())) {
                HlhtOperatorSetting hlhtOperatorSetting = hlhtOperatorSettingService.selectByTenantCodeAndOperatorId(tenantCode, gun.getHlhtOperatorId());
                if (hlhtOperatorSetting.getStationOpenforWx().equals("1")) {
                    return DataTResponse.FAIL("公众号暂不开放当前站点！ ");
                }
            }
            if (!tenantCode.equals(gun.getTenantCode())) {
                HlhtTenantOpen hlhtTenantOpen = hlhtTenantOpenService.selectHlhtTenantOpenBySaas(tenantCode, gun.getTenantCode(), "0");
                if (hlhtTenantOpen == null) {
                    return DataTResponse.FAIL("未开放互联关系");
                }
                HlhtTenantOpenStation hlhtTenantOpenStation = hlhtTenantOpenStationService.selectByhlhtTenantOpenStationBySaas(tenantCode, gun.getTenantCode(),
                        gun.getElecStationId(), "0");
                if (hlhtTenantOpenStation == null) {
                    return DataTResponse.FAIL("未开放该互联站点");
                }
            }

            ElecPile pile = elecPileService.selectPileByPileId(gun.getElecPileId());
            if (pile.getStatus() == 0) {
                return DataTResponse.FAIL("充电桩已经离线");
            }

            //判断是否在充电订单
            /***/
            OrderInfo orderInfo = orderInfoService.selectOrderByGunIdAndMember(gun.getElecGunId(), member.getMemberId(), member.getTenantCode());
            if (orderInfo != null) {
                DataTResponse dataTResponse = DataTResponse.SUCCESS();
                dataTResponse.setStatus(201);
                dataTResponse.setMessage("存在正在充电的订单");
                //DataTResponse.put(orderInfo.getOutOrderNum());
                return dataTResponse;
            }
        }
        //判断当前时间是否存在电价
        ElecStationPriceSearch elecStationPriceSearch = new ElecStationPriceSearch();
        elecStationPriceSearch.setElecStationId(gun.getElecStationId());
        elecStationPriceSearch.setTenantCode(tenantCode);
        ElecStationPrice elecStationPrice = elecStationPriceService.getCurrentPrice(elecStationPriceSearch);
        if (elecStationPrice == null) {
            return DataTResponse.FAIL("该站点当前时间段没有设置电价，请联系客服");
        }


        ElecPile pile = elecPileService.selectPileByPileId(gun.getElecPileId());

        GunVo vo = new GunVo(gun);
        BeanUtils.copyProperties(gun, vo);
        if (pile != null) {
            //运营中的桩
            if ("1".equals(pile.getOperateStatus())) {
                vo.setPower(pile.getPower());
                if (pile.getPileElecType() == 1 || pile.getPileElecType() == 3 || pile.getPileElecType() == 5 || pile.getPileElecType() == 6) {
                    vo.setPileType("0");
                } else {
                    vo.setPileType("1");
                }
                //枪状态
                if (gun.getElecPileId().equals(pile.getElecPileId())) {
                    //离线 使用状态 0 空闲 1使用中  2 插枪中  3故障 4 离线
                    if (0 == pile.getStatus()) {
                        vo.setUsingStatus(4);
                    } else {
                        //正常
                        if (0 == gun.getNormalStatus()) {
                            vo.setUsingStatus(gun.getStatus());
                            if (255 == vo.getUsingStatus()) {
                                vo.setUsingStatus(3);
                            }
                            if (3 == gun.getStatus()) {
                                vo.setUsingStatus(5);
                            }
                        } else {
                            vo.setUsingStatus(3);
                        }
                    }
                }
                //是否在充电中
                if (1 == gun.getStatus() && gun.getHlhtOperatorId() == null) {
                    vo.setSoc(new BigDecimal(chargeService.getCurrDataSoc(gun, tenantCode)));
                }
                if (1 == gun.getStatus() && gun.getHlhtOperatorId() != null) {
                    vo.setSoc(new BigDecimal(hlhtChargeService.getCurrDataSoc(gun, tenantCode, gun.getHlhtOperatorId())));
                }
                if (1 == gun.getStatus()) {
                    OrderInfoExample orderInfoExample = new OrderInfoExample();
                    orderInfoExample.createCriteria().andStatusEqualTo("1").andElecGunIdEqualTo(gun.getElecGunId());
                    OrderInfo orderInfo = orderInfoService.selectByExample(orderInfoExample).stream().findFirst().orElseGet(() -> null);
                    if (orderInfo != null) {
                        vo.setSurplusTime(chargeService.getRemainChargingTime(orderInfo.getOrderNum()));
                    }
                }
            } else if ("0".equals(pile.getOperateStatus())) {
                return DataTResponse.FAIL("运营状态:未上线");
            }
        }
        if (gun.getNormalStatus() != 0) {
            return DataTResponse.FAIL("当前枪存在故障！");
        } else if (gun.getStatus() == 1) {
            return DataTResponse.FAIL("当前枪使用中！");
        } else if (!"1".equals(gun.getOperateStatus())) {
            return DataTResponse.FAIL("当前枪已下线！");
        } else {
//            HashMap<String, Object> responseData = new HashMap<>();
//            responseData.put("gunNo", gun.getGunNo());
//            responseData.put("elecStationId", gun.getElecStationId());
//            logger.info("gunNo:{},elecStationId:{}", gun.getGunNo(), gun.getElecStationId());
//            DataTResponse DataTResponse = DataTResponse.SUCCESS();
////            DataTResponse.put(gun.getGunNo());
////            DataTResponse.put(gun.getElecStationId());
//            DataTResponse.put(responseData);
            return DataTResponse.SUCCESS_DATA(vo);
        }

    }

    /**
     * 开始充电
     */
    @ResponseBody
    @RequestMapping(value = "/query_start_charge", method = RequestMethod.POST)
    @ApiOperation(value = "开始充电", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            //@ApiImplicitParam(name = "hlhtTenantCode", paramType = "query", value = "SAAS内互联互通的设备商", required = false),
            //@ApiImplicitParam(name = "hlhtOperatorId", paramType = "query", value = "第三方互联互通的设备商", required = false),
            @ApiImplicitParam(name = "elecStationId", paramType = "query", value = "桩群ID", required = true),
            @ApiImplicitParam(name = "elecGunId", paramType = "query", value = "枪ID", required = true),
            @ApiImplicitParam(name = "limitSoc", paramType = "query", value = "预设SOC", required = false),
            @ApiImplicitParam(name = "preTime", paramType = "query", value = "预充电时间（s 秒）", required = false),
            @ApiImplicitParam(name = "preAmount", paramType = "query", value = "预充电金额（元）", required = false),
            //@ApiImplicitParam(name = "startType", paramType = "query", value = " 启动方式 0:充满为止 1:时间控制充电  2:金额控制充电  3:电量控制充电 默认0", required = false),
            //@ApiImplicitParam(name = "startValue", paramType = "query", value = "启动策略 时间单位为 1 秒  金额单位为 1 元  电量单位为 kw 默认0", required = false),
            @ApiImplicitParam(name = "accountType", paramType = "query", value = "支付的账户类型 0个人钱包 1企业钱包 3先付后退钱包", required = true),
            //@ApiImplicitParam(name = "ticketUsingType", paramType = "query", value = "是否优先使用优惠卷,0使用 1不使用,默认0", required = false),
            @ApiImplicitParam(name = "isUseGiveAmount", paramType = "query", value = "0，否，1是使用权益金", required = false),
            @ApiImplicitParam(name = "memberTicketIds", paramType = "query", value = "优惠卷id,多个用逗号分割", required = false),
            @ApiImplicitParam(name = "carNum", paramType = "query", value = "车牌号", required = true)})
    public DataTResponse<WxStartChargeResult> query_start_charge(HttpServletRequest request, String hlhtTenantCode, String hlhtOperatorId,
                                                                 Long elecGunId, Integer limitSoc, String accountType, String isUserGiveAmount,
                                                                 @RequestParam(value = "isUseGiveAmount", defaultValue = "0") String isUseGiveAmount,
                                                                 @RequestParam(value = "ticketUsingType", defaultValue = "0") String ticketUsingType,
                                                                 String carNum, BigDecimal preAmount, Integer preTime, String memberTicketIds) {
        // startType;   //
        //startValue;//
        String startType = "0";
        String startValue = "0";
        if (preTime != null && preTime.toString() != "") {
            startValue = preTime.toString();
            startType = "1";
        }

        if (preAmount != null && preAmount.toString() != "") {
            startValue = preAmount.toString();
            startType = "2";
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        String tenantCode = loginInfo.getTenantCode();

        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("ChargeController.query_start_charge.tenantCode:{}:mobile:{},elecGunId:{},carNum:{}", tenantCode, member.getMobile(), elecGunId, carNum);
        if ("1".equals(member.getStatus())) {
            return DataTResponse.FAIL("会员已被冻结");
        }

        //支付的账户类型 0个人钱包 1企业钱包  默认就是个人钱包
        if (accountType == null) {
            accountType = "0";
        }

        if (StringUtils.isBlank(member.getMobile())) {
            return DataTResponse.FAIL("未绑定手机号");
        }

        if ("1".equals(accountType) && "2".equals(member.getMemberType())) {
            //查询子会员是否被冻结
            EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberService.selectByPrimaryKey(member.getMemberId());
            if ("2".equals(enterpriseSubmember.getStatus())) {
                return DataTResponse.FAIL("当前子会员身份已被冻结");
            }
        }
        if ("1".equals(accountType)) {
            isUseGiveAmount = "0";
            EnterpriseSubmemberApplyExample enterpriseSubmemberApplyExample = new EnterpriseSubmemberApplyExample();
            enterpriseSubmemberApplyExample.createCriteria().andMemberIdEqualTo(member.getMemberId());
            EnterpriseSubmemberApply enterpriseSubmemberApply = enterpriseSubmemberApplyService.selectByExample(enterpriseSubmemberApplyExample)
                    .stream().findFirst().orElseGet(() -> null);

            if (enterpriseSubmemberApply != null && "1".equals(enterpriseSubmemberApply.getStatus())) {
                return DataTResponse.FAIL("您的企业账户被禁用，请联系管理员~");
            }
        }
        //用户账户
        MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(member.getMemberId());
        if (memberAccount == null) {
            return DataTResponse.FAIL("用户账户不存在");
        }

        OrderInfo orderInfoNotEnd = orderInfoService.selectByNotEnd(member.getMemberId());
        if (orderInfoNotEnd != null) {
            return DataTResponse.FAIL("上一次充电待结算");
        }

        ElecGun elecGun = elecGunService.selectByPrimaryKey(elecGunId);

        if (elecGun == null) {
            return DataTResponse.FAIL("未找到对应充电枪");
        }

        //normal_status 是否正常0：正常255：故障默认0’，
        if (elecGun.getNormalStatus() == 255) {
            return DataTResponse.FAIL("该充电枪故障,请选择其他");
        } else if (elecGun.getNormalStatus() == 1) {
            return DataTResponse.FAIL("枪锁故障,请选择其他");
        }

        //operate_status运营状态：0未上线1上线2下线默认0'，
        if (!"1".equals(elecGun.getOperateStatus())) {
            return DataTResponse.FAIL("该充电桩未上线,请选择其他");
        }

        if (elecGun.getStatus() == 1) {
            return DataTResponse.FAIL("当前充电枪使用中");
        }

        if (elecGun.getStatus() == 1) {
            return DataTResponse.FAIL("当前充电枪使用中");
        }

        //获取不同钱包对应余额
        BigDecimal moeny = memberAccountService.getAccountByChargeType(memberAccount, accountType);
        logger.info("启动充电的账户类型 accountType:{},moeny:{}", accountType, moeny);

        //判断当前时间是否存在电价
        ElecStationPriceSearch elecStationPriceSearch = new ElecStationPriceSearch();
        elecStationPriceSearch.setElecStationId(elecGun.getElecStationId());
        elecStationPriceSearch.setTenantCode(tenantCode);
        ElecStationPrice elecStationPrice = elecStationPriceService.getCurrentPrice(elecStationPriceSearch);

        if (elecStationPrice == null) {
            return DataTResponse.FAIL("该站点当前时间段没有设置电价，请联系客服");
        }
        BigDecimal minAmount = elecStationPrice.getElecPrice().add(elecStationPrice.getServicePrice());
        RcSetting rcSetting = rcSettingService.selectByExample(new RcSettingExample()).stream().findFirst().orElseGet(() -> null);
        if (rcSetting != null) {
            if (((rcSetting.getBmsPower().multiply(minAmount))
                    .add(rcSetting.getOccupyAmount())).compareTo(moeny) > 0) {
                return DataTResponse.FAIL("钱包余额不足");
            }
        }


        TResponse tResponse = chargeServiceRouter.checkStartMemberAccount(member, memberAccount, hlhtTenantCode, hlhtOperatorId, accountType);

        DataTResponse dataTResponse = new DataTResponse();
        BeanUtils.copyProperties(tResponse, dataTResponse);
        if (dataTResponse.getStatus() != HttpConstant.STATUS_SUCCESS) {
            return dataTResponse;
        }

        //查询桩群中的服务器域名
        ElecStation elecStation = elecStationService.selectByPrimaryKey(elecGun.getElecStationId());
        //组装启动信息
        CommandStartReq commandStartReq = new CommandStartReq();
        commandStartReq.setTenantCode(tenantCode);
        commandStartReq.setMemberTicketIds(memberTicketIds);

        commandStartReq.setStartValue(startValue);
        commandStartReq.setStartType(startType);
        commandStartReq.setTenantOperatorCode(elecStation.getTenantOperatorCode());
        commandStartReq.setHlhtTenantCode(elecStation.getHlhtTenantCode());
        if (!tenantCode.equals(elecStation.getTenantCode())) {
            //其它SAAS运营商桩
            hlhtTenantCode = elecStation.getTenantCode();
            commandStartReq.setHlhtTenantCode(hlhtTenantCode);
        }
        commandStartReq.setHlhtOperatorId(elecStation.getHlhtOperatorId());
        commandStartReq.setMemberId(member.getMemberId());

        String osType = request.getHeader(HttpConstant.OS_TYPE);
        if ("app".equals(osType)) {
            commandStartReq.setOrderSource("1");
        } else {
            //订单来源 0 公众号 1 APP  2小程序 3.刷卡 4.VIN码充电   9.第三方API  默认0
            commandStartReq.setOrderSource("2");
        }
        commandStartReq.setElecStationId(elecGun.getElecStationId());
        commandStartReq.setElecPileId(elecGun.getElecPileId());
        commandStartReq.setElecGunId(elecGun.getElecGunId());
        commandStartReq.setGunNo(elecGun.getGunNo());
        commandStartReq.setGunNum(elecGun.getGunNum());
        commandStartReq.setPreAmount(preAmount);
        commandStartReq.setPreTime(preTime);
        commandStartReq.setAccountType(accountType);
        if (ticketUsingType != null) {
            commandStartReq.setTicketUsingType(ticketUsingType);
        } else {
            commandStartReq.setTicketUsingType(WebConstant.CON1);
        }

        if (carNum == null) {
            TenantCarNumber tenantCarNumber = tenantCarNumberService.selectDefaultCarNumber(member.getMemberId());
            String oriCarNum = null;
            if (tenantCarNumber != null) {
                if (tenantCarNumber.getCarArea() != null) {
                    oriCarNum += tenantCarNumber.getCarArea();
                }
                if (tenantCarNumber.getCarLetter() != null) {
                    oriCarNum += tenantCarNumber.getCarLetter();
                }
                if (tenantCarNumber.getCarNum() != null) {
                    oriCarNum += tenantCarNumber.getCarNum();
                }
            }
            if (StringUtils.isNotBlank(oriCarNum)) {
                try {
                    //carNum = URLEncoder.encode(oriCarNum, "UTF-8");
                    carNum = URLDecoder.decode(oriCarNum, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    //carNum = "";
                    return DataTResponse.FAIL("无默认车牌号");
                }
            } else {
                return DataTResponse.FAIL("无默认车牌号");
            }
        }


        try {
            TResponse tResponse2 = chargeServiceRouter.assembleStartChargeResult(commandStartReq, member, hlhtTenantCode, hlhtOperatorId, elecStation, elecGun,
                    limitSoc, accountType, ticketUsingType, carNum);
            //请求启动充电
            DataTResponse dataTResponse2 = new DataTResponse();
            BeanUtils.copyProperties(tResponse2, dataTResponse2);

            return dataTResponse2;
        } catch (Exception e) {
            logger.error("发送启动充电指令失败", e);
            return DataTResponse.FAIL("处理失败");
        }
    }

    /**
     * 充电过程读取数据
     */
    @ResponseBody
    @RequestMapping("/query_equip_charge_status")
    @ApiOperation(value = "充电过程读取数据", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            //@ApiImplicitParam(name = "hlhtTenantCode", paramType = "query", value = "SAAS内互联互通的设备商", required = false),
            //@ApiImplicitParam(name = "hlhtOperatorId", paramType = "query", value = "第三方互联互通的设备商", required = false),
            @ApiImplicitParam(name = "outOrderNum", paramType = "query", value = "外部订单号", required = true)})
    public DataTResponse<WxEquipChargeStatusResult> query_equip_charge_status(HttpServletRequest request, String hlhtTenantCode, String hlhtOperatorId, String outOrderNum) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        String tenantCode = loginInfo.getTenantCode();

        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        if (outOrderNum == null) {
            return DataTResponse.FAIL("非法的订单号码");
        }
        logger.info("ChargeController.query_equip_charge_status.tenantCode:{}:mobile:{},outOrderNum:{}", tenantCode, member.getMobile(), outOrderNum);
        OrderComment orderComment = null;

        Long elecStationId = null;
        Long elecPileId = null;

        orderComment = orderCommentService.selectOrderByOutOrderNum(outOrderNum);
        if (orderComment == null) {
            logger.info("查询充电状态,非法的订单号码:{}", outOrderNum);
            return DataTResponse.FAIL("非法的订单号码");
        }

        elecStationId = orderComment.getElecStationId();
        elecPileId = orderComment.getElecPileId();

        //查询桩群中的服务器域名
        ElecStation elecStation = elecStationService.selectByPrimaryKey(elecStationId);

        //组装启动信息
        CommandStartReq commandStartReq = new CommandStartReq();
        commandStartReq.setTenantCode(orderComment.getTenantCode());
        commandStartReq.setTenantOperatorCode(orderComment.getTenantOperatorCode());
        if (!tenantCode.equals(elecStation.getTenantCode())) {
            //其他SAAS运营商桩
            hlhtTenantCode = elecStation.getTenantCode();
            commandStartReq.setHlhtTenantCode(hlhtTenantCode);
        }
        commandStartReq.setHlhtOperatorId(orderComment.getHlhtOperatorId());
        commandStartReq.setOutOrderNum(outOrderNum);
        commandStartReq.setElecStationId(elecStationId);
        commandStartReq.setElecPileId(elecPileId);

        try {
            //请求充电信息
            TResponse tResponse = chargeServiceRouter.assembleEquipChargeStatusResult(commandStartReq, member, orderComment, hlhtTenantCode, hlhtOperatorId);

            DataTResponse dataTResponse = new DataTResponse();
            BeanUtils.copyProperties(tResponse, dataTResponse);
            return dataTResponse;
        } catch (Exception e) {
            logger.error("查询充电状态失败", e);
            return DataTResponse.FAIL("处理失败");
        }
    }

    /**
     * 执行发送终止充电命令(只发送命令,需检查是否发送成功以及在成功后轮询订单状态)
     */
    @ResponseBody
    @RequestMapping(value = "/query_stop_charge", method = RequestMethod.POST)
    @ApiOperation(value = "结束充电", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            //@ApiImplicitParam(name = "hlhtTenantCode", paramType = "query", value = "SAAS内互联互通的设备商", required = false),
            //@ApiImplicitParam(name = "hlhtOperatorId", paramType = "query", value = "第三方互联互通的设备商", required = false),
            @ApiImplicitParam(name = "outOrderNum", paramType = "query", value = "外部订单号", required = true)})
    public DataTResponse<StopChargeResult> query_stop_charge(HttpServletRequest request, String hlhtTenantCode, String hlhtOperatorId, String outOrderNum) {
        //if (StringUtils.isBlank(tenantCode)) {
        //    logger.error("找不到对应运营商信息:{}", tenantCode);
        //    return DataTResponse.FAIL("找不到对应运营商信息");
        //}

        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        String tenantCode = loginInfo.getTenantCode();
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("ChargeController.query_stop_charge.tenantCode:{}:mobile:{},outOrderNum:{}", tenantCode, member.getMobile(), outOrderNum);

        OrderComment orderComment = orderCommentService.selectOrderByOutOrderNum(outOrderNum);
        if (orderComment == null) {
            return DataTResponse.FAIL("非法的订单号码");
        }

        ElecGun elecGun = elecGunService.selectByPrimaryKey(orderComment.getElecGunId());

        //查询桩群中的服务器域名
        ElecStation elecStation = elecStationService.selectByPrimaryKey(orderComment.getElecStationId());

        CommandStopReq commandStopReq = new CommandStopReq();
        commandStopReq.setTenantCode(tenantCode);
        commandStopReq.setTenantOperatorCode(elecStation.getTenantOperatorCode());
        commandStopReq.setHlhtTenantCode(elecStation.getHlhtTenantCode());
        if (!tenantCode.equals(elecStation.getTenantCode())) {
            //其它SAAS运营商桩
            hlhtTenantCode = elecStation.getTenantCode();
            commandStopReq.setHlhtTenantCode(hlhtTenantCode);
        }
        commandStopReq.setHlhtOperatorId(elecStation.getHlhtOperatorId());

        commandStopReq.setMemberId(member.getMemberId());

        commandStopReq.setElecStationId(orderComment.getElecStationId());
        commandStopReq.setElecPileId(elecGun.getElecPileId());
        commandStopReq.setElecGunId(elecGun.getElecGunId());
        commandStopReq.setGunNo(elecGun.getGunNo());
        commandStopReq.setGunNum(elecGun.getGunNum() != null ? elecGun.getGunNum() : null);

        OrderInfo orderInfo = null;
        //非正向互联桩
        if (StringUtils.isBlank(hlhtTenantCode) || StringUtils.isBlank(hlhtOperatorId)) {
            orderInfo = orderInfoService.selectOrderByOutOrderNum(outOrderNum);
            if (orderInfo == null) {
                logger.warn("query_stop_charge 找不到订单号，1分钟后挂单,{}", outOrderNum);
                return DataTResponse.FAIL("处理失败");
            }
            commandStopReq.setOrderId(orderInfo.getOrderId());
            //补充订单信息
            orderComment.setOrderId(orderInfo.getOrderId());
            orderComment.setStartTime(orderInfo.getStartTime());
        }

        commandStopReq.setOrderNum(orderComment.getOrderNum());
        commandStopReq.setOutOrderNum(orderComment.getOutOrderNum());

        try {

            TResponse tResponse = chargeServiceRouter.assembleStopChargeResult(commandStopReq, member, orderComment, elecGun, hlhtTenantCode, hlhtOperatorId);
            DataTResponse dataTResponse = new DataTResponse();
            BeanUtils.copyProperties(tResponse, dataTResponse);
            return dataTResponse;
        } catch (Exception e) {
            logger.error("发送停止充电命令失败", e);
            return DataTResponse.FAIL("处理失败");
        }

    }

    /**
     * 发送终止命令成功后轮询订单状态
     */
    @ResponseBody
    @RequestMapping(value = "/refreshStop")
    @ApiOperation(value = "发送终止命令成功后轮询订单状态（未完成）", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "outOrderNum", paramType = "query", value = "外部订单号", required = true)})
    public DataTResponse<OrderRefreshVo> refreshStop(HttpServletRequest request, String outOrderNum) {
        //if (StringUtils.isBlank(tenantCode)) {
        //    logger.error("找不到对应运营商信息:{}", tenantCode);
        //    return DataTResponse.FAIL("找不到对应运营商信息");
        //}

        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        String tenantCode = loginInfo.getTenantCode();
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("ChargeController.refreshStoptenantCode:{},mobile:{},outOrderNum{}", tenantCode, member.getMobile(), outOrderNum);

        OrderInfo orderInfo = orderInfoService.selectOrderByOutOrderNum(outOrderNum);
        if (orderInfo == null) {
            return DataTResponse.FAIL("非法的订单号码");
        }

        if (!orderInfo.getMemberId().equals(member.getMemberId())) {
            return DataTResponse.FAIL("订单会员跟登录会员不一致,请重新登录");
        }

        ElecStation elecStation = elecStationService.selectByPrimaryKey(orderInfo.getElecStationId());
        if (elecStation != null) {
            orderInfo.setElecStationName(elecStation.getStationName());
        }

        ElecPile elecPile = elecPileService.selectByPrimaryKey(orderInfo.getElecPileId());
        if (elecPile != null) {
            orderInfo.setElecPileName(elecPile.getPileName());
            orderInfo.setPileNo(elecPile.getPileNo());
        }
        ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfo.getElecGunId());

        OrderRefreshVo orderRefreshVo = new OrderRefreshVo();
        UgsMemberLevelRecord ugsMemberLevelRecord = ugsMemberLevelRecordService.selectByOrderId(orderInfo.getOrderId());
        if (ugsMemberLevelRecord != null) {
            orderRefreshVo.setGrowingValue(ugsMemberLevelRecord.getAfterValue() - ugsMemberLevelRecord.getBeforeValue());
        } else {
            orderRefreshVo.setGrowingValue(0);
        }
        //OrderInfo转换OrderRefreshVo
        orderRefreshVo = dozerMapper.map(orderInfo, OrderRefreshVo.class);

        addOrderData(orderInfo, orderRefreshVo, elecStation, elecGun);

        List<OrderDiscountVo> orderDiscountVos = orderDiscountRecordService.listOrderDiscountVo(orderInfo.getOrderId());
        orderRefreshVo.setOrderDiscountVoList(orderDiscountVos);
        orderRefreshVo.setSurplusTime(chargeService.getRemainChargingTime(orderInfo.getOrderNum()));
        orderRefreshVo.setTotalPower(orderRefreshVo.getTotalPower() == null ? BigDecimal.ZERO
                : orderRefreshVo.getTotalPower().setScale(3, BigDecimal.ROUND_HALF_UP));
        return DataTResponse.SUCCESS_DATA(orderRefreshVo);

    }

    /**
     * （注意：当正向互联时才需要.........）
     * 挂单处理,超过1分钟未成功启动,将订单修改为"挂单"状态
     */
    //@Transactional
    //@ResponseBody
    //@RequestMapping(value = "/query_suspend_charge", method = RequestMethod.POST)
    //@ApiOperation(value = "挂单处理(需要登录)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "hlhtTenantCode", paramType = "query", value = "SAAS内互联互通的设备商", required = true),
    //        @ApiImplicitParam(name = "hlhtOperatorId", paramType = "query", value = "第三方互联互通的设备商", required = true),
    //        @ApiImplicitParam(name = "outOrderNum", paramType = "query", value = "外部订单号", required = true)})
    //public DataTResponse query_suspend_charge(@ApiIgnore HttpSession session, String hlhtTenantCode, String hlhtOperatorId, String outOrderNum) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
    //        logger.error("找不到对应运营商信息:{}", tenantCode);
    //        return DataTResponse.FAIL("找不到对应运营商信息");
    //    }
    //
    //    LoginInfoVo loginInfo = readLoginInfo(request);
    //    if (loginInfo == null) {
    //        return DataTResponse.FAIL_LOGIN();
    //    }
    //    MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
    //    if (member == null) {
    //        return DataTResponse.FAIL_LOGIN();
    //    }
    //
    //    logger.info("ChargeController.query_suspend_charge request:{},:{},:{},:{}", member.getMemberId(), hlhtTenantCode, hlhtOperatorId, outOrderNum);
    //
    //    OrderComment orderComment = orderCommentService.selectOrderByOutOrderNum(outOrderNum);
    //    OrderInfo orderInfo = orderInfoService.selectOrderByOutOrderNum(outOrderNum);
    //
    //    if (orderComment == null) {
    //        logger.info("查询充电状态,非法的订单号码:{}", outOrderNum);
    //        return DataTResponse.FAIL("非法的订单号码");
    //    }
    //    if (orderInfo != null) {
    //        if ("2".equals(orderInfo.getStatus()) || "4".equals(orderInfo.getHlhtOrderStatus())) {
    //            logger.info("当前订单已经结算，订单状态为:{}", orderInfo.getStatus());
    //            return DataTResponse.FAIL("当前订单已经结算");
    //        }
    //        orderInfo.setHlhtOrderStatus(HlhtOrderStatusEnum.HlhtOrderStatus5.getCode());
    //        orderInfo.setLastUpdatedTime(new Date());
    //        orderInfoService.updateByPrimaryKeySelective(orderInfo);
    //    }
    //    //订单状态 5:挂单(1分钟内未启动成功)
    //    orderComment.setHlhtOrderStatus(HlhtOrderStatusEnum.HlhtOrderStatus5.getCode());
    //    orderComment.setLastUpdatedTime(new Date());
    //    orderCommentService.updateByPrimaryKeySelective(orderComment);
    //    //如果单充用户 (charge_type ==0) ,修改充电状态(charge_status用户是否在充电 0不是，1正充电)
    //    MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(orderInfo.getMemberId());
    //    if (memberInfo != null) {
    //        if ("0".equals(memberInfo.getChargeType())) {
    //            memberInfo.setChargeStatus("0");
    //            memberInfoService.updateByPrimaryKeySelective(memberInfo);
    //        }
    //    }
    //    return DataTResponse.SUCCESS();
    //}

    /**
     * 补充订单数据（排放量，枪相关信息）
     */
    private OrderRefreshVo addOrderData(OrderInfo order, OrderRefreshVo orderRefreshVo, ElecStation elecStation, ElecGun elecGun) {
        //如果没收到结算推送,就没有 lastTime
        if (order.getEndTime() != null) {
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+0"));
            Date date = new Date(order.getEndTime().getTime() - order.getStartTime().getTime());
            orderRefreshVo.setChargeLastTime(formatter.format(date));
        } else {
            orderRefreshVo.setChargeLastTime("");
        }

        //碳排放量 电量*0.12
        orderRefreshVo.setCarbonEmission(order.getTotalPower().multiply(new BigDecimal("0.12")).setScale(2, BigDecimal.ROUND_HALF_DOWN));
        orderRefreshVo.setGunNo(elecGun.getGunNo());
        orderRefreshVo.setElecStationName(elecStation.getStationName());
        orderRefreshVo.setAddress(elecStation.getAddress());
        orderRefreshVo.setGunNum(elecGun.getGunNum());
        return orderRefreshVo;
    }

    /**
     * 枪编码兼容
     */
    private QrCodeVo checkGunNo(QrCodeVo qrCodeVo) {
        ElecGun gun = elecGunService.selectByGunNo(qrCodeVo.getGunNo());
        //星充兼容
        if (gun == null) {
            String qrCode = qrCodeVo.getGunNo();
            if (qrCode.length() == 8) {
                qrCode = "110000000000000" + qrCode + "000";
            }
            if (qrCode.length() == 10) {
                qrCode = "120000000000000" + qrCode.substring(0, qrCode.length() - 2) + "0" + qrCode.substring(qrCode.length() - 2);
            }
            gun = elecGunService.selectByGunNo(qrCode);
            if (gun != null) {
                qrCodeVo.setHlhtOperatorId(gun.getHlhtOperatorId() != null ? gun.getHlhtOperatorId() : null);
                qrCodeVo.setGunNo(gun.getGunNo());
            }
        }
        return qrCodeVo;
    }


}
